//
//  ILMusicViewController.m
//  ILife
//
//  Created by lanou on 15/10/26.
//  Copyright © 2015年 ILife. All rights reserved.
//

#import "ILMusicViewController.h"
#import "ILMusicListModel.h"
#import "ILMusicListTableViewCell.h"
#import "ILMusicDetailViewController.h"
#import <MJRefresh.h>
#import "ILMusicRandomViewController.h"
#import "FMDatabase.h"
@interface ILMusicViewController ()<UITableViewDataSource, UITableViewDelegate>
{
    NSInteger pageNo;
    NSInteger pageSize;
}
@property(nonatomic, strong)NSMutableArray *dataSourceArray;
@property(nonatomic, strong)UITableView *mainListTableView;
@property(nonatomic, strong)FMDatabase *dataBase;

@end

@implementation ILMusicViewController


-(NSMutableArray *)dataSourceArray
{
    if (_dataSourceArray == nil) {
        self.dataSourceArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSourceArray;
}

-(void)requestData
{
 
    NSString *htmlStr =[NSString stringWithFormat:@"http://wawa.fm/CmsSite/a/cms/article/mylist?category.id=543&pageNo=%ld&pageSize=%ld&uid=0",(long)pageNo,(long)pageSize];
    NSURL *url = [NSURL URLWithString:htmlStr];
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:10];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if(data != nil){
        if (pageNo == 1) {
        [self.dataSourceArray removeAllObjects];
        [_dataBase executeUpdate:@"delete from ILMusic"];
        }
        
       NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
        if (![str isEqualToString:@""]) {
            NSArray *arr = [str componentsSeparatedByString:@"("];
            NSString *dataStr = [[arr[1] componentsSeparatedByString:@")"] objectAtIndex:0];
            NSData *realData = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
            NSArray *realArr = [NSJSONSerialization JSONObjectWithData:realData options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            for (NSDictionary *dic in realArr) {
                ILMusicListModel *model = [[ILMusicListModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                [self.dataSourceArray addObject:model];
                
                
                [_dataBase executeUpdate:@"insert into ILMusic(musicId ,image, songname) values (?,?,?)",model.musicId, model.image,model.articleData.songname];
                
            }
            
            
        }
       [_mainListTableView reloadData];
       [_mainListTableView.header endRefreshing];
       [_mainListTableView.footer endRefreshing];
        }else
        {
            NSLog(@"数据请求失败");

        }
    }];
    
}
- (void)popClickAction:(id)sender
{
    ILMusicRandomViewController *randomVC = [[ILMusicRandomViewController alloc]init];
    [self.navigationController pushViewController:randomVC animated:YES];
    
}
// 返回顶部
- (void)toTop
{
    [self.mainListTableView scrollRectToVisible:CGRectMake(0, 20, 1, 1) animated:NO];
}




- (void)viewDidLoad {
    [super viewDidLoad];
//    [self.navigationItem.backBarButtonItem setTintColor:[UIColor blackColor]];
    [[UINavigationBar appearance] setTintColor:[UIColor blackColor]];
    UIBarButtonItem *popItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"shake"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(popClickAction:)];
    self.navigationItem.rightBarButtonItem = popItem;
    self.navigationItem.title = @"音乐人";
    //self.navigationController.hidesBarsOnSwipe = YES;
    pageSize = 5;
    _mainListTableView = [[UITableView alloc]initWithFrame:self.view.bounds];
    _mainListTableView.delegate = self;
    _mainListTableView.dataSource = self;
    
    [_mainListTableView registerClass:[ILMusicListTableViewCell class] forCellReuseIdentifier:@"ILMusicListTableViewCell"];
    [self MJRefresh];
    [self.view addSubview:_mainListTableView];
    
    // 回到顶部按钮
    UIButton *topButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [topButton setImage:[UIImage imageNamed:@"top"] forState:(UIControlStateNormal)];
    topButton.frame = CGRectMake(SCREEN_WIDTH - 60, SCREEN_HEIGHT - 100, 40, 40);
    topButton.backgroundColor = [UIColor grayColor];
    topButton.alpha = 0.5;
    topButton.layer.cornerRadius = 20;
    topButton.layer.masksToBounds = YES;
    [topButton addTarget:self action:@selector(toTop) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:topButton];
    
    
    
#pragma 数据持久化
    
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"ILive.db"];
    
    _dataBase = [FMDatabase databaseWithPath:filePath];
    NSLog(@"filePath = %@",filePath);
    if ([_dataBase open]) {
        NSLog(@"数据库dddd打开成功");
//        [_dataBase executeUpdate:@"drop table ILMusic"];
        [_dataBase executeUpdate:@"create table ILMusic(musicId text, image text, songname text)"];
    }else
    {
        NSLog(@"数据库ddddd打开失败");
    }
//    
    FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"select *from ILMusic"];
    while ([resultSet next]) {
        NSString *image = [resultSet stringForColumn:@"image"];
        NSString *songname = [resultSet stringForColumn:@"songname"];
        NSString *musicId = [resultSet stringForColumn:@"musicId"];
        ILMusicListModel *musicListModel = [[ILMusicListModel alloc]init];
        musicListModel.image= image;
        musicListModel.articleData.songname = songname;
        musicListModel.musicId = musicId;
        [self.dataSourceArray addObject:musicListModel];
    }
    
}

// mj刷新
-(void)MJRefresh
{
    _mainListTableView.header = [MJRefreshHeader headerWithRefreshingBlock:^{
        
    }];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [header setTitle:@"一支穿云箭，千军万马来相见" forState:MJRefreshStateRefreshing];
    _mainListTableView.header = header;
    [_mainListTableView.header beginRefreshing];
    
    _mainListTableView.footer = [MJRefreshFooter footerWithRefreshingBlock:^{
        
    }];
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadFooterData)];
    [footer setTitle:@"一支穿云箭，千军万马来相见" forState:MJRefreshStateIdle];
    [footer setTitle:@"主人！正在召唤其他小伙伴" forState:MJRefreshStateRefreshing];
    
    footer.stateLabel.font = [UIFont systemFontOfSize:15];
    _mainListTableView.footer =footer;
}
// 上拉加载
-(void)loadFooterData
{
    if (self.dataSourceArray.count != 0)
    {
       pageNo++;
    }
    [self requestData];
}
// 下拉刷新
-(void)loadNewData
{
    pageNo = 1;
    [self requestData];
}
#pragma UITableViewDatasource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSourceArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ILMusicListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ILMusicListTableViewCell" forIndexPath:indexPath];
    ILMusicListModel *model = self.dataSourceArray[indexPath.row];
    cell.musicListModel = model;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 30 + SCREEN_WIDTH*2/3;
}
#pragma UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ILMusicListModel *model = self.dataSourceArray[indexPath.row];
    if (model != nil && model.image != nil && ![model.image isEqualToString:@""]) {
        ILMusicDetailViewController *detailVC = [[ILMusicDetailViewController alloc]init];
        detailVC.musicID = model.musicId;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
